package document;

import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;

import util.Pair;


public class Document 
{
	public Document()
	{
		entries = new Vector<DocumentEntry>();
		normalised = false;
	}
	
	public void addEntry(DocumentEntry d)
	{
		normalised = false;
		entries.add(d);
	}
	
	public Vector<DocumentEntry> getEntries()
	{
		if(!normalised)
		{
			normaliseDocument(entries);
		}
		return entries;
	}
	
	public Vector<DocumentEntry> getEntriesSorted(int count)
	{
		Vector<DocumentEntry> result = new Vector<DocumentEntry>();
		if(!normalised)
		{
			normaliseDocument(entries);
		}
		Collections.sort(entries, new CompareScores());
		for(int i=0; i<count && i < entries.size(); i++)
		{
			result.add(new DocumentEntry(entries.get(i).getTerm(),entries.get(i).getScore()));
		}
		normaliseDocument(result);
		return result;
	}
	
	public void normaliseDocument(Vector<DocumentEntry> what)
	{
		double length = 0;
		double scale = 0;
		for(DocumentEntry e : what)
		{
			length += e.getScore()*e.getScore();
		}
		length = Math.sqrt(length);
		scale = 1.0/length;
		for(DocumentEntry e : what)
		{
			e.setScore(e.getScore()*scale);
		}
		normalised = true;
	}
	
	private class CompareScores implements Comparator<DocumentEntry>
	{

		@Override
		public int compare(DocumentEntry arg0,
				DocumentEntry arg1) {
			if(arg0.getScore()< arg1.getScore())
			{
				return 1;
			}
			else if(arg0.getScore() == arg1.getScore())
			{
				return 0;
			}
			else
			{
				return -1;
			}
			 
		}
		
	}
	
	protected Vector<DocumentEntry> entries;
	protected boolean normalised;
}
